//
//  UITextView + emoticon.swift
//  Emotion
//
//  Created by 曹晓龙 on 15/10/24.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit

// MARK: - 图片表情转textView 文本
extension UITextView {
    ///  返回图片表情完整字符串文本
    var emoticonText:String {
        let text = attributedText
        
        var strM  = String()
        
        text.enumerateAttributesInRange(NSRange(location: 0, length: text.length), options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? CXLEmoticonAttachment {
                
                strM += attachment.emoticon.chs ?? ""
                
            }else{
                
                let str = (text.string as NSString) .substringWithRange(range)
                
                strM += str
                
            }
        }
        
        return strM
    }
    
    
    ///  添加图片表情
    func loadTextViewText(emoticon:CXLEmoticon){
        
        if emoticon.isEmptyBtn {
            return
        }
        
        if emoticon.isRemoveBtn {
            
            deleteBackward()
            
            return
        }
        
        if emoticon.emoji != nil {
            
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            
            return
        }
        
        loadTextViewImage(emoticon)
    
        delegate?.textViewDidChange?(self)
        
    }
    
    /// 添加图片信息
    private func loadTextViewImage(emoticon:CXLEmoticon){

        // 获取图文信息
        let imageText = CXLEmoticonAttachment(emoticon: emoticon).getImageText(font!)
        
        // 记录当前的输入框内容
        let strm = NSMutableAttributedString(attributedString: attributedText)
        
        // 插入图片文本
        strm.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        // 记录光标的位置
        let range = selectedRange
        
        // 替换文本
        attributedText = strm
        
        // 移动光标
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}
